package com.graph;

import java.util.*;

public class Solution417 {
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        int m = heights.length;
        int n = heights[0].length;
        boolean[][] reach1 = new boolean[m][n];
        boolean[][] reach2 = new boolean[m][n];
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            dfs(heights, reach1, i, 0);
            dfs(heights, reach2, i, n - 1);
        }
        for (int i = 0; i < n; i++) {
            dfs(heights, reach1, 0, i);
            dfs(heights, reach2, m - 1, i);
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (reach1[i][j] && reach2[i][j]) {
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(i);
                    tmp.add(j);
                    res.add(tmp);
                }
            }
        }
        return res;
    }

    public void dfs(int[][] heights, boolean[][] reach, int i, int j) {
        if (reach[i][j]) return;
        reach[i][j] = true;
        if (i - 1 >= 0 && heights[i - 1][j] >= heights[i][j]) dfs(heights, reach, i - 1, j);
        if (i + 1 <= heights.length - 1 && heights[i + 1][j] >= heights[i][j]) dfs(heights, reach, i + 1, j);
        if (j - 1 >= 0 && heights[i][j - 1] >= heights[i][j]) dfs(heights, reach, i, j - 1);
        if (j + 1 <= heights[0].length - 1 && heights[i][j + 1] >= heights[i][j]) dfs(heights, reach, i, j + 1);
    }
}
